package com.soosync.servlet;

import java.util.HashMap;

import com.soosync.common.AbstractHttpServlet;
import com.soosync.common.BaseException;
import com.soosync.common.PropertyManager;
import com.soosync.common.SQLManager;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
public class AppServlet extends AbstractHttpServlet {

	private static final long serialVersionUID = 1L;

	public static HashMap<String, Integer> funcMap = new HashMap<String, Integer>();

	static {
		funcMap.put("getapps", new Integer(1));
		funcMap.put("addapp", new Integer(2));
	}

	protected void process() {
		try {
			String func = requestBox.getString("func");
			Integer idx = (Integer) funcMap.get(func);
			switch (idx.intValue()) {
			case 1:
				getapps();
				break;
			case 2:
				addapp();
				break;
			default:
				break;
			}
		} catch (JSONException e) {
		
		}catch (NullPointerException e){
			try {
				resultBox.put("code", "ER0003");
				resultBox.put("data", e);
				return;
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

	private void getapps() throws JSONException {
		String uid = requestBox.getString("uid");
		String suid = (String) session.getAttribute("suid");
		if(!uid.equals(suid)){
			resultBox.put("code", "ER0002");
			return;
		}
		
		JSONObject resultjo = new JSONObject();
		JSONArray hotapps = new JSONArray();
		JSONArray userapps = new JSONArray();
		
		String code = "OK0000";
		String error = null;
		try {
			String query = PropertyManager.getProperty("app.module.info");
			hotapps = (JSONArray) SQLManager.select("appSource", query, new Object[] {}, hotapps);
			query = PropertyManager.getProperty("user.app.info");
			userapps = (JSONArray) SQLManager.select("appSource", query, new Object[] { suid }, userapps);
			resultjo.put("hotapps", hotapps);
			resultjo.put("userapps", userapps);
		} catch (BaseException e) {
			code = "ER0000";
			error = e.toString();
		}
		if(error == null){
			resultBox.put("data", resultjo);
		}else{
			resultBox.put("data", error);
		}
		resultBox.put("code", code);
	}
	
	private void addapp() throws JSONException {
		String uid = requestBox.getString("uid");
		String suid = (String) session.getAttribute("suid");
		if(!uid.equals(suid)){
			resultBox.put("code", "ER0002");
			return;
		}
		
		JSONObject resultjo = new JSONObject();
		String code = "OK0000";
		String error = null;
		try {
			String query = PropertyManager.getProperty("app.add");
			SQLManager.select("appSource", query, new Object[] { suid });
			resultjo.put("hotapps", hotapps);
			resultjo.put("userapps", userapps);
		} catch (BaseException e) {
			code = "ER0000";
			error = e.toString();
		}
		if(error == null){
			resultBox.put("data", resultjo);
		}else{
			resultBox.put("data", error);
		}
		resultBox.put("code", code);
	}
}